package com.lwm.transactional.annotation.utils;

import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务管理相关 开启事务、提交事务、回滚事务、释放连接
 *
 * @author liweimin
 * @date 2021/6/10 16:15
 * @since
 */
@Component
@Aspect
public class TransactionManager {

    @Autowired
    private ConnectionUtils connectionUtils;

    @Pointcut("execution(* com.lwm.transactional.annotation.service.impl.*.*(..))")
    private void pt() {
    }

    public TransactionManager() {
    }

    public TransactionManager(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    /**
     * 开启事务
     */
    @Before("pt()")
    public void start() {
        try {
            connectionUtils.getConnection().setAutoCommit(false);
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    @AfterReturning("pt()")
    public void commit() {
        try {
            connectionUtils.getConnection().commit();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    @AfterThrowing("pt()")
    public void rollback() {
        try {
            Connection connection = connectionUtils.getConnection();
            connection.rollback();
        } catch (SQLException throwable) {
            System.out.println("事务回滚异常");
            throwable.printStackTrace();
        }
    }

    /**
     * 释放连接
     */
    @After("pt()")
    public void release() {
        try {
            connectionUtils.getConnection().close();//还回连接池
            connectionUtils.removeConnection();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }
}
